package juc.base;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CompletableFutureDemo {
    /*这种写法可以按照线程的完成情况先后拿到结果不阻塞*/
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                    System.out.println("job1 start");
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "job1 data";
                })
                /*这种写法可以按照线程的完成情况先后拿到结果不阻塞*/
                .whenComplete((s, throwable) -> System.out.println(s))
                .exceptionally(throwable -> {
                    throwable.printStackTrace();
                    return "excption";
                });
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
                    System.out.println("job2 start");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "job2 data";
                }).whenComplete((s, throwable) -> System.out.println(s))
                .exceptionally(throwable -> {
                    throwable.printStackTrace();
                    return "excption";
                });
        /*这里阻塞*/
//        System.out.println(future2.get());
//        System.out.println(future.get());
//        System.out.println(future2.get());

        TimeUnit.SECONDS.sleep(6);
    }
}